import router from './router';
import { createAction } from 'redux-actions';
import { WorkView, getWorkViewByPath } from './workViews';
import { ThunkAction } from 'redux';

const _addWorkView = createAction<WorkView>('ADD_WORK_VIEW', view => view);
const _removeWorkView = createAction<WorkView>('REMOVE_WORK_VIEW', view => view); 

export const addWorkView = (path: string): ThunkAction<void, any, any> => (dispatch, getStates) => {
  const view = getWorkViewByPath(path);
  if (view) {
    dispatch(_addWorkView(view));
  }
};

export const removeWorkView = (view: WorkView): ThunkAction<void, any, any> => (dispatch, getStates) => {
  const workViews = getStates(). workViewReducer;
  const count = workViews.length;
  const _workViews = workViews as Array<WorkView>;
  const index = _workViews.findIndex(item => item.path === view.path);

  dispatch(_removeWorkView(view));

  // 剩余2个和2个以上的标签页
  if (count >= 2) {
    if (view.isActive) {
      const diff = index === count - 1 ? -1 : 1;
      location.hash = workViews[index + diff].path;
    }
  } else {
    // 关闭最后一个标签页，跳转到首页
    location.hash = '#/';
  }
};

export const bindWorkViewRouter = (): ThunkAction<void, any, any> => (dispatch, getStates) => {
  router.on(/.*/, () => dispatch(addWorkView(location.hash)));
};
